package ysf.com.mediumdifficulty;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author ysf
 * @date 2021/7/1 22:26
 */
public class SixteenthDemos {

    public static void main(String[] args) {
        int[] nums = new int[]{-1,2,1,-4};
        int target = 1;
        int i = threeSumClosest(nums, target);
        System.out.println(i);
    }


    public static int threeSumClosest(int[] nums,int target){
        // 对数组进行排序
        Arrays.sort(nums);
        int sub = Integer.MAX_VALUE;
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            int lo = i+1,hi = nums.length-1;
            while (lo<hi){
                if(Math.abs((nums[lo]+nums[hi]+nums[i]-target))<sub){
                    sum = nums[lo] + nums[hi] + nums[i];
                        sub = Math.abs(sum - target);
                }
                if (nums[lo] + nums[hi] + nums[i]>target){
                    hi--;
                }else {
                    lo++;
                }
            }
        }
        return sum;
    }


    @Test
    public void test(){
        // 取正数
        int abs = Math.abs(10);
        System.out.println(abs);
    }


}
